﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Seven.Site.Mvc.Attributes
{
    /// <summary>
    /// 异常忽略处理
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class IgnoreExceptionAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 是否记录异常信息
        /// </summary>
        private bool Record { get; set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="record">是否记录异常信息</param>
        public IgnoreExceptionAttribute(bool record = true)
        {
            this.Record = record;
        }

        /// <summary>
        /// 在发生异常时调用
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            if (this.Record)
            {
                var r = filterContext.RouteData; var context = filterContext.HttpContext;
                string c = r.Values["controller"].ToString();
                string a = r.Values["action"].ToString();
                string userName = context.User.Identity.Name;
                if (string.IsNullOrWhiteSpace(userName)) { userName = "guest"; }
                Seven.Site.Log.FileLoger.WriteLog("[" + userName + "]发生异常——异常信息：" + filterContext.Exception.Message + "；所在Controller：" + c + "；所在Action：" + a + "；");
            }

            filterContext.ExceptionHandled = true;

            base.OnException(filterContext);
        }
    }
}
